﻿using Core.Authorization;
using Core.Identity.Common.Interfaces.Common.Interfaces;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace Core.Tenant.Features.GetById;

/// <summary>
/// 获取租户权限
/// </summary>
public class GetTenantPermissionByIdQuery : IRequest<IEnumerable<Guid?>>
{
    /// <summary>
    /// 租户ID
    /// </summary>
    public required string TenantId { get; set; }
}

public class GetTenantPermissionByIdQueryHandler :
         IRequestHandler<GetTenantPermissionByIdQuery, IEnumerable<Guid?>>
{
    private readonly IIdentityDbContext _context;

    public GetTenantPermissionByIdQueryHandler(
        IIdentityDbContext context)
    {
        _context = context;
    }

    public async Task<IEnumerable<Guid?>> Handle(GetTenantPermissionByIdQuery request, CancellationToken cancellationToken)
    {
        if (request.TenantId == TenantConstants.Root.Id)
        {
            throw new BoilerplateException("默认租户权限禁止查看");
        }
        return await _context.TenantPermissions
            .Where(x => x.BoilerplateTenantInfoId == request.TenantId)
            .Select(x => x.PermissionId)
            .ToListAsync(cancellationToken);
    }
}
